package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CastExceptions;
import com.qk.common.exception.CommomException;
import com.qk.common.util.JwtUtil;
import com.qk.domain.User.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements com.qk.management.service.UserService {
  private static final String DEFAULT_PASSWORD_SUFIX = "123";
  private static final Integer USER_STATUS_NORMAL = 1;
  private static final Integer USER_STATUS_USNNORMAL = 0;
   @Autowired
   private UserMapper userMapper;
   @Autowired
   private RoleMapper roleMapper;
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if(hasNull){
            CommomException.throwException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        if(Objects.isNull(dbUser)){
            CommomException.throwException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        if(ObjectUtil.equal(dbUser.getStatus(),USER_STATUS_USNNORMAL)){
            CommomException.throwException(ParamEnum.LOGIN_STATUS_ERROR);
        }

        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodedPassword = dbUser.getPassword();
        boolean isChecked = ObjectUtil.equal(encodedPassword, userPassword);
        if(!isChecked){
            CommomException.throwException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }

        Role role = roleMapper.selectById(dbUser.getRoleId());
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .rolelabel(role.getLabel())
                .token(JwtUtil.generateToken(claims))
                .build();
    }
    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }
    @Override
    public User getById(Integer id) {
        if(Objects.isNull(id)){
            CommomException.throwException(ParamEnum.PARAM_ERROR);
        }
        return userMapper.selectById(id);
    }



    @Override
    public void deleteBatch(List<Integer> ids) {
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if(!isNotEmpty){
            CommomException.throwException(ParamEnum.PARAM_ERROR);
        }
        userMapper.deleteBatch(ids);
    }




    @Override
    public void add(User user) {
        boolean hasNull =BeanUtil.hasNullField( user,"id","password","deptId","roleId","image","remark","updateTime","createTime");
        if(hasNull){
            CastExceptions.throwException(ParamEnum.PARAM_ERROR);
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        String password = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);

    }

    @Override
    public PageResult<UserDO> list(UserDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
     List<UserDO> result = userMapper.selectByPage(dto);
     Page<UserDO> page = (Page<UserDO>) result;
     return PageResult.<UserDO>builder().
             total(page.getTotal())
             .rows(page.getResult())
             .build();

    }


}
